package Demo86;

import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * 直接修改写法
 * 先修改周围的为 . 然后再修改
 */

class Solution1 {
    char[][] board;
    int m,n;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public void solve(char[][] board) {
        this.board = board;
        m = board.length;
        n = board[0].length;

        // 处理行
        for(int j = 0; j < n; j++) {
            if(board[0][j] == 'O') bfs(0,j);
            if(board[m-1][j] == 'O') bfs(m-1,j);
        }
        // 处理列
        for(int i = 0; i < m; i++) {
            if(board[i][0] == 'O') bfs(i,0);
            if(board[i][n - 1] == 'O') bfs(i, n - 1);
        }
        // 还原.为O和更改O为X
//        for (int i = 0; i < m; i++) {
//            for (int j = 0; j < n; j++) {
//                if(board[i][j] == '.') {
//                    board[i][j] = 'O';
//                }else if(board[i][j] == 'O') {
//                    board[i][j] = 'X';
//                }
//            }
//        }
    }

    private void bfs(int i, int j) {
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] {i,j});
        board[i][j] = '.';
        while(!q.isEmpty()) {
            int[] t = q.poll();
            for (int k = 0; k < 4; k++) {
                int x = t[0] + dx[k], y = t[1] + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O') {
                    q.add(new int[] {x,y});
                    board[x][y] = '.';
                }
            }
        }
    }
}
class Demo1 {
    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
//        char[][] board =  new char[][] {{'O','X','O','O','X','X'},{'O','X','X','X','O','X'},{'X','O','O','X','O','O'},{'X','O','X','X','X','X'},{'O','O','X','O','X','X'},{'X','X','O','O','O','O'}};
        char[][] board =  new char[][] {{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}};
        for (char[] chs : board) {
            for(char ch : chs) {
                System.out.print(ch + " ");
            }
            System.out.println();
        }
        solution1.solve(board);
        System.out.println("================================");
        for (char[] chs : board) {
            for(char ch : chs) {
                System.out.print(ch + " ");
            }
            System.out.println();
        }
    }
}
